﻿#include "additem.h"
#include "ui_additem.h"

AddItem::AddItem(QWidget *parent, const QStringList &topics) :
    QDialog(parent),
    ui(new Ui::AddItem)
{
    ui->setupUi(this);

    table=TD_NOTE;

    ui->topics->addItems(topics);
    ui->topics->addItem(MANUAL_INPUT);
    ui->topics->setCurrentIndex(-1);
}

AddItem::~AddItem()
{
    delete ui;
}

void AddItem::on_topics_currentTextChanged(const QString &text)
{
    if(text == MANUAL_INPUT)
    {
        ui->topic->clear();
        ui->topic->setEnabled(true);
    }
    else
    {
        ui->topic->setText(text);
        ui->topic->setEnabled(false);
    }
}

bool AddItem::addItem(const QString &topic,
                      const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (topic,detail) values (?,?)")
                  .arg(table));
    query.addBindValue(topic);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddItem::on_btn_submit_clicked()
{
    QString topic=ui->topic->text().trimmed();
    if(topic.isEmpty())
        topic=DEF_TOPIC;

    QString detail=ui->detail->toPlainText().trimmed();
    if(detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    if(addItem(topic,detail))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}

